package yanyi.community.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import yanyi.community.dto.CommentDTO;
import yanyi.community.dto.QuestionDTO;
import yanyi.community.enums.CommentTypeEnum;
import yanyi.community.exception.CustomizeErrorCode;
import yanyi.community.exception.CustomizeException;
import yanyi.community.service.CommentService;
import yanyi.community.service.QuestionService;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
public class QuestionController {
    @Autowired
    private QuestionService questionService;
    @Autowired
    private CommentService commentService;

    @GetMapping("/question/{id}")
    public String question(@PathVariable Long id, Model model, HttpServletRequest request) {
        if (id == null||id==0) {
            throw new CustomizeException(CustomizeErrorCode.INVALID_INPUT);
        }
        QuestionDTO question = questionService.getById(id);
        if (question != null) {
            List<QuestionDTO> relatedList=questionService.selectRelated(question);
            //增加阅读数
            questionService.updateViewCount(id);
           List<CommentDTO> commentDTOS=commentService.getListByTargetId(id, CommentTypeEnum.QUESTION);
            model.addAttribute("question", question);
            model.addAttribute("comments",commentDTOS);
            model.addAttribute("relatedList",relatedList);
        } else {
            throw new CustomizeException(CustomizeErrorCode.INVALID_INPUT);
        }
        return "question";
    }
}
